package so.shanku.essential.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.UserOrderAdapter;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.Utils;
import striveen.util.used.view.view.XListView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/9.
 * 售后列表  已完成的订单
 */
public class ProductAfterMarketActivity extends BaseUIActivity implements UserOrderAdapter.UserOrderItemCompountClickListener {
	@ViewInject(id = R.id.xlistview_order)
	private XListView xlistview_order;
	private UserOrderAdapter userOrderAdapter;
	/**
	 * 无相关数据
	 */
	@ViewInject(id = R.id.nodata_layout,click = "nodata_layout_click")
	private LinearLayout nodata_layout;
    /**
     * 退款进度
     */
    @ViewInject(id = R.id.refund_progress_tv,click = "refund_progress_tv_click")
    private TextView refund_progress_tv;
    /**
     * 退货进度
     */
    @ViewInject(id = R.id.return_goods_progress_tv,click = "return_goods_progress_tv_click")
    private TextView return_goods_progress_tv;

    /**
     * 标记本界面内容类型 1：售后  2：退款详情
     */
    private int flag=1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_affter_market);
        setCenter_title(R.string.aftermarket_server);
		//titleLayout.setVisibility(View.GONE);
		//linearlayout_search.setVisibility(View.VISIBLE);
		//setCenter_title(R.string.user_order);
//		setBtn_menu(R.drawable.search, new View.OnClickListener() {
//			@Override
//			public void onClick(View view) {
//				order_search_click();
//			}
//		});
//        search_ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//
//                    key = search_ed.getText().toString();
//                    getSearchOrder(true);
//                    return true;
//                }
//                return false;
//            }
//        });
		//search_ed.setHint(R.string.search_all_order);
		xlistview_order.setXListViewListener(xListLoadMore);
        loadingToast.show();
        getSearchOrder(true);
	}

    /**
     * 退湖进度
     * @param view
     */
    public void return_goods_progress_tv_click(View view){
        jumpTo(ScanReturnGoodsRecordsActivity.class);
    }

    /**
     * 退款进度
     * @param view
     */
    public void refund_progress_tv_click(View view){
        jumpTo(ScanRefundRecordsActivity.class);
    }


    public void nodata_layout_click(View view){
       // loadingToast.show();
        //getSearchOrder(true);
    }
	XListView.IXListViewListener xListLoadMore = new XListView.IXListViewListener() {
		@Override
		public void onRefresh() {
            getSearchOrder(true);
		}

		@Override
		public void onLoadMore() {
            getSearchOrder(false);
        }
	};

	/**
	 * 我的订单接口
	 */
	private int pageSize = 10;
	private int page = 0;
	private List<JsonMap<String, Object>> data_OrderList;
	private void getSearchOrder(boolean chearAllData) {
		if (chearAllData) {
			data_OrderList = null;
			if (userOrderAdapter != null) {
				userOrderAdapter.notifyDataSetChanged();
			}
			page = 0;
			xlistview_order.setPullRefreshEnable(true);
			xlistview_order.setPullLoadEnable(true);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("UserId", Utils.getUserId(this));
		params.put("currentPage", page + 1);
		params.put("pageSize", pageSize);

		GetDataQueue queue = new GetDataQueue();
		queue.setCallBack(callBack);
		queue.setActionName(GetDataConfing.Action_GetOrderByUid);
		queue.setWhat(GetDataConfing.What_GetOrderByUid);
		queue.setParamsNoJson(params);
		getDataUtil.getData(queue);
	}
	private void setAdatper_singleSortlist(final List<JsonMap<String, Object>> data) {

		if (data.size() == 0 || data.size() % pageSize != 0) {
			xlistview_order.setPullLoadEnable(false);
		}
		if (page == 0) {
			this.data_OrderList = data;
			userOrderAdapter = new UserOrderAdapter(this,data_OrderList);
            userOrderAdapter.setTag(1);
			xlistview_order.setAdapter(userOrderAdapter);
            userOrderAdapter.setUserOrderItemCompountClickListener(this);
		} else {
			this.data_OrderList.addAll(data);
			userOrderAdapter.notifyDataSetChanged();
		}
		page++;

	}
    /**
     * 获取服务器数据的返回信息
     */
    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isOkAndCodeIsNot1(mContext,
                        entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_GetOrderByUid) {
                        List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info);
                        setAdatper_singleSortlist(data);
                    } else if (entity.what == GetDataConfing.What_GetHistoryUserOrderByPageNum) {
                        List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info);

                        setAdatperDataByPageNum(data);
                    } else if (entity.what == GetDataConfing.what_UpdateOrdersbyOrderNum) {
                        toast.showToast(R.string.shopping_order_option_success);
                        getHistoryOders();
                    } else if (entity.what == GetDataConfing.What_ReturnFundByOrderNum) {
                        getHistoryOders();
                        toast.showToast(R.string.shopping_order_option_success);
                    } else if (entity.what == GetDataConfing.What_ConfirmOrdersByOrderNum) {
                        getHistoryOders();
                        toast.showToast(R.string.shopping_order_option_success);

                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
            invalidateListData();
            xlistview_order.stopLoadMore();
            xlistview_order.stopRefresh();
        }
    };

    /**
     * 设置数据 并华东到上个位置
     *
     * @param data
     */
    private void setAdatperDataByPageNum(final List<JsonMap<String, Object>> data) {

        if (data.size() == 0 || data.size() % pageSize != 0) {
            xlistview_order.setPullLoadEnable(false);
        }
        this.data_OrderList = data;
        userOrderAdapter = new UserOrderAdapter(this, data_OrderList);
        xlistview_order.setAdapter(userOrderAdapter);
        userOrderAdapter.setTag(1);
        userOrderAdapter.setUserOrderItemCompountClickListener(this);
        if(firstItemPosition<data_OrderList.size()) {
            xlistview_order.setSelection(firstItemPosition);
        }
    }

    /**
     * 记录当前显示的第一个item的位置
     */
    int firstItemPosition = 0;

    /**
     * 获取历史以查询的订单
     */
    private void getHistoryOders() {
         getSearchOrder(true);
//        firstItemPosition = xlistview_order.getFirstVisiblePosition();
//        page = 0;
//        loadingToast.show();
//        data_OrderList = null;
//        if (userOrderAdapter != null) {
//            userOrderAdapter.notifyDataSetChanged();
//        }
//        xlistview_order.setPullRefreshEnable(true);
//        xlistview_order.setPullLoadEnable(true);
//        Map<String, Object> params = new HashMap<String, Object>();
//        params.put(GetDataQueue.Params_key,"orderCreateTime");
//        params.put("userName", Utils.getUserAccount(this));
//        params.put("currentPage", page + 1);
//        params.put("pageSize", pageSize);
//        params.put("condition",key);
//        GetDataQueue queue = new GetDataQueue();
//        queue.setCallBack(callBack);
//        queue.setActionName(GetDataConfing.GetAction_SelectOrdersBySearch);
//        queue.setWhat(GetDataConfing.what_SelectOrdersBySearch);
//        queue.setParamsNoJson(params);
//        getDataUtil.getData(queue);
    }



    private void invalidateListData() {
        if (data_OrderList == null || data_OrderList.size() < 1) {
            xlistview_order.setVisibility(View.GONE);
            nodata_layout.setVisibility(View.VISIBLE);
        } else {
            xlistview_order.setVisibility(View.VISIBLE);
            nodata_layout.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(isNeedRefreshData) {
            isNeedRefreshData=false;
            getHistoryOders();
        }
    }

    JsonMap jsonMap;
    private boolean isNeedRefreshData=false;
    @Override
    public void userOrderItemCompountClick(int position, Constant.UserOrderItemType userOrderItemType,int childPosition) {
        jsonMap = data_OrderList.get(position);
        String orderNum = jsonMap.getStringNoNull("OrderNum");
        isNeedRefreshData=true;
        if(userOrderItemType== Constant.UserOrderItemType.SEE_PRODUCT){
//            ArrayList<JsonMap<String,Object>> dataList = (ArrayList<JsonMap<String, Object>>) jsonMap.getList_JsonMap("OrderdetailList");
//            String productId=dataList.get(childPosition).getStringNoNull("ProductId");
//            seeProductDetail(productId);
            seeOrderDetail(orderNum);
        }else if (userOrderItemType == Constant.UserOrderItemType.SEELogistics) {
            isNeedRefreshData=false;
            seeLogistics(orderNum);
        } else if (userOrderItemType == Constant.UserOrderItemType.SEE_ORDER_DETAIL) {
            seeOrderDetail(orderNum);
        } else if (userOrderItemType == Constant.UserOrderItemType.SEE_BRAND) {
            isNeedRefreshData=false;
            seeShopDetail(jsonMap.getStringNoNull("shopId"));
        } else if (userOrderItemType == Constant.UserOrderItemType.CANCEL_ORDER) {
            getData_Cancel_Order(orderNum, callBack);
        } else if (userOrderItemType == Constant.UserOrderItemType.ORDER_CONFIRM) {
            goodsReceiveConfirm(orderNum, callBack);
        } else if (userOrderItemType == Constant.UserOrderItemType.FUND_RETURN) {
            getFundReturn(orderNum, callBack);
        } else if (userOrderItemType == Constant.UserOrderItemType.GOODS_RETURN) {
            getGoodsReturn(orderNum, callBack);
        } else if (userOrderItemType == Constant.UserOrderItemType.GOTO_PAY) {

        }else if (userOrderItemType== Constant.UserOrderItemType.DO_GOODS_RETURN){
            doGoodsReturn(orderNum, jsonMap.getStringNoNull("VendorId"));
        }else if (userOrderItemType == Constant.UserOrderItemType.REFUND_DETAIL) {
            isNeedRefreshData=false;
            scanRefundDetail(orderNum);
        }

    }


}
